package com.ujs.leetcode.Intersection;

import java.util.*;

/**
 * @author zhangshihao
 * @create 2023-10-14 20:19
 * <p>
 * 349. 两个数组的交集
 * https://leetcode.cn/problems/intersection-of-two-arrays/description/
 */
public class Intersection {
    public static void main(String[] args) {
        int[] nums1 = {4, 9, 5};
        int[] nums2 = {9, 4, 9, 8, 4};
        int[] intersection = intersection(nums1, nums2);
        System.out.println(Arrays.toString(intersection));
    }

    public static int[] intersection(int[] nums1, int[] nums2) {
        int[] record = new int[1000];
        Set<Integer> set = new HashSet<>();  // 为了防止重复，将结果设置为set类型
        for (int j : nums1) {
            record[j]++;
        }
        for (int j : nums2) {
            if (record[j] > 0) {
                set.add(j);
            }
        }
        System.out.println("set类型的结果" + set);
        // 将set类型的结果转换为int[]
        int[] result = new int[set.size()];
        Iterator<Integer> it = set.iterator();
        int count = 0;
        while (it.hasNext()) {
            result[count] = it.next();
            count++;
        }
        return result;
    }


    public static int[] intersection2(int[] nums1, int[] nums2) {
        HashSet<Integer> set1 = new HashSet<>();
        HashSet<Integer> resSet = new HashSet<>();
        for (int i : nums1) {
            set1.add(i);
        }
        for (int i : nums2) {
            if (set1.contains(i)) {
                resSet.add(i);
            }
        }
        //方法1：将结果集合转为数组
        return resSet.stream().mapToInt(x -> x).toArray();

        //方法2：另外申请一个数组存放setRes中的元素,最后返回数组
        // int[] arr = new int[resSet.size()];
        // int j = 0;
        // for(int i : resSet){
        //     arr[j++] = i;
        // }
        // return arr;
    }
}
